package com.wei.czz.framework.admin.helper;

import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.enums.common.multiDIct.MultiDictEnum;
import com.wei.czz.common.utils.CopyUtils;
import com.wei.czz.framework.admin.entity.UserRoleEntity;
import com.wei.czz.framework.admin.service.RoleService;
import com.wei.czz.framework.admin.service.UserRoleService;
import com.wei.czz.framework.common.entity.MultiDictEntity;
import com.wei.czz.framework.common.service.MultiDictService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2024-06-04 15:45:16
 * className: DeptHelper 部门帮助类
 * version: 1.0
 * description:
 */
@Component
@AllArgsConstructor
public class DeptHelper {

    private static final Logger log = LoggerFactory.getLogger(DeptHelper.class);

    private final RoleService roleService;

    private final UserRoleService userRoleService;

    private final MultiDictService multiDictService;

    /**
     * 获取用户直接管理的部门主键列表
     * @param userId 用户主键
     * @return 部门主键列表
     */
    public List<Long> getManageDeptIdList(Long userId) {

        /*
            获取用户关联角色
         */
        List<UserRoleEntity> userRoleList = userRoleService.findList(userId, null, CommonEnum.ZERO.getValue());
        if (userRoleList.isEmpty()) {
            return Collections.emptyList();
        }
        List<String> roleIdList = CopyUtils.mapList(userRoleList, userRole -> userRole.getRoleId().toString());

        /*
            获取角色管理的部门字典
         */
        List<MultiDictEntity> multiDictList = multiDictService.findDirectChildrenList(MultiDictEnum.DEPT_MANAGER,
                roleIdList);
        // 收集部门主键
        return multiDictList.stream()
                .map(multiDict -> {
                    if (StringUtils.isBlank(multiDict.getValue())) {
                        log.warn("级联字典字符串值为空。id={}", multiDict.getId());
                        return null;
                    }
                    try {
                        return Long.parseLong(multiDict.getValue().trim());
                    } catch (Exception e) {
                        log.error("级联字典配置部门主键值错误。id={} value={} message={}", multiDict.getId(),
                                multiDict.getValue(), e.getMessage(), e);
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}
